package comet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;

import javax.servlet.AsyncContext;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sun.core.json.JSONObject;

import com.google.gson.Gson;
import com.sun.app.service.ServiceManager;
import com.sun.core.bean.BeanManager;
import com.sun.util.AnalysisBrowser;

import comet.vo.Host;

public class ChatServlet extends HttpServlet {
	private static final long serialVersionUID = -277914015930424042L; 
	private static ServiceManager sermger = (ServiceManager) BeanManager
			.getBean("ServiceManager");

		// TODO Auto-generated constructor stub
	private final ChatManage instance = ChatManage.getInstance();

	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		instance.startOnlineThread();
		instance.startSysMessageTread();
		instance.startMsgThread();
	}

	// GET method is used to establish a stream connection
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		if(request.getSession().getAttribute("UID")!=null){
			String userid = (String) request.getSession().getAttribute("UID");
				//写入前台
				String id = CreateAsyncId(response, userid);
				//初始化用户信息
				Host myHost = new Host();
				myHost.setUserid(id);
				myHost.setUsername(sermger.getFriendService().getUserName(userid));
				myHost.setPhoto(sermger.getUserService().getPhotoByUID(userid));
				AsyncContext ac = request.startAsync();
				AsyncListener myListener = new MyAsyncListener(myHost);
				ac.addListener(myListener);
				ac.setTimeout(600000);
				myHost.setAsync(ac);
				myHost.setFriends(instance.getFriendsList(myHost));
				System.out.println(myHost.getFriends()+"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
				instance.pullAllOnlineFriends(myHost);
				instance.pullUser(myHost);
				//将我加入推送队列
				instance.addUser(myHost);
				//初始化我自己的好友列表
		}
	}

	// POST method is used to communicate with the server
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		// close-request
		AsyncContext ac = instance.getCurrentAsync(request);
		if (ac == null) {
			return;
		}
		// close-request
		if ("close".equals(request.getParameter("metadata.type"))) {
			String hostId = request.getParameter("metadata.id");
			instance.removeHost(hostId);
			request.getSession().removeAttribute("UID");
			return;
		}

		// send-request
		Map<String, Object> data = new LinkedHashMap<String, Object>();
		data.put("userid", request.getParameter("touser"));
		data.put("fromUserId", request.getParameter("userid"));
		data.put("message", request.getParameter("message"));
		instance.pullMessage(data);
		System.out.println("doPost"+data);
		

	}

	@Override
	public void destroy() {
		//messages.clear();
	}
	
	public String CreateAsyncId(HttpServletResponse response,String myId) throws IOException{
		// Content-Type header
		response.setContentType("text/plain");
		response.setCharacterEncoding("utf-8");

		// Access-Control-Allow-Origin header
		response.setHeader("Access-Control-Allow-Origin", "*");

		PrintWriter writer = response.getWriter();

		// Id
		final String id = myId;
		writer.print(id);
		writer.print(';');

		// Padding
		for (int i = 0; i < 1024; i++) {
			writer.print(' ');
		}
		writer.print(';');
		writer.flush();
		return id;
	}

	
	class MyAsyncListener implements AsyncListener{
		public Host h;
		public MyAsyncListener(Host host){
			this.h=host;
		}
		public void onComplete(AsyncEvent event) throws IOException {
			instance.removeHost(h.getUserid());
			System.out.println("完成");
		}

		public void onTimeout(AsyncEvent event) throws IOException {
			instance.removeHost(h.getUserid());
			System.out.println("超时");
		}

		public void onError(AsyncEvent event) throws IOException {
			instance.removeHost(h.getUserid());
			System.out.println("报错");
		}

		public void onStartAsync(AsyncEvent event) throws IOException {

		}
	}
}
